using System.IO;
using System.IO.Compression;
using System.Text;
using System.Xml.Linq;

namespace RRX.Xml.Helper
{
    public static class CompressionHelper
    {
        public static string XElementToCompressedBase64(XElement element)
        {
            // 1️⃣ XML in String konvertieren
            string xmlString = element.ToString(SaveOptions.DisableFormatting);

            // 2️⃣ UTF-8 Bytes erzeugen
            byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlString);

            // 3️⃣ GZIP-Kompression durchführen
            using var output = new MemoryStream();
            using (var gzip = new GZipStream(output, CompressionLevel.Optimal))
                gzip.Write(xmlBytes, 0, xmlBytes.Length);

            // 4️⃣ In Base64 kodieren
            return Convert.ToBase64String(output.ToArray());
        }


        public static XElement CompressedBase64ToXElement(string base64)
        {
            // 1️⃣ Base64 in Byte-Array umwandeln
            byte[] compressedBytes = Convert.FromBase64String(base64);

            // 2️⃣ Entpacken mit GZIP
            using var input = new MemoryStream(compressedBytes);
            using var gzip = new GZipStream(input, CompressionMode.Decompress);
            using var decompressed = new MemoryStream();
            gzip.CopyTo(decompressed);

            // 3️⃣ Bytes wieder zu UTF-8-String und dann XElement
            string xmlString = Encoding.UTF8.GetString(decompressed.ToArray());
            return XElement.Parse(xmlString);
        }

        public static string CompressedBase64ToString(string base64)
        {
            // 1️⃣ Base64 in Byte-Array umwandeln
            byte[] compressedBytes = Convert.FromBase64String(base64);

            // 2️⃣ Entpacken mit GZIP
            using var input = new MemoryStream(compressedBytes);
            using var gzip = new GZipStream(input, CompressionMode.Decompress);
            using var decompressed = new MemoryStream();
            gzip.CopyTo(decompressed);

            // 3️⃣ Bytes wieder zu UTF-8-String und dann XElement
            string xmlString = Encoding.UTF8.GetString(decompressed.ToArray());
            return xmlString;
        }


    }

}

